package com.MyApp.CompanyRank;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import au.com.bytecode.opencsv.CSVReader;

/** 
 * this class does not depends on wikipedia class, just read the dbpedia file, no need to cache entire wiki in the beginning.
 * 
 * @author nick
 *
 */
public class CSVTable {
	String[] schemaRow;
	
	List<String[]> table = null;
	
	/** 
	 * read from a csv file and form a table. Each row is an array of Strings, and key is specified by the column number.
	 * 
	 * @param filename
	 * @param keyCol
	 * @throws IOException
	 */
	public CSVTable(String filename) throws IOException {
		this(new File(filename));
	}
	
	public CSVTable(File file) throws IOException {
		
		readTableFile(file);
	}
	
	public String[] getRow(int rowNumber) {	
		return table.get(rowNumber);
	}
	
	/**
	 * given the name of the column, return the column in a list
	 * @param colName
	 * @return
	 */
	public List<String> getColumn(String colName) {
		for (int i = 0; i< schemaRow.length; i++) {
			if (schemaRow[i].equals(colName))
				return getColumn(i);
		}
		return null;
	}
	
	/**
	 * given the column number, return the column in a list
	 * 
	 * @param col
	 * @return
	 */
	public List<String> getColumn(int col) {
		ArrayList<String> ret = new ArrayList<String>(table.size());
		for (int i = 0; i< table.size(); i++) {
			String[] s = table.get(i);
			if (col<s.length) {
				String r = s[col];
				ret.add(r);
			}
		}
		return ret;
	}
	
	
	void readTableFile(File file) throws IOException {
		table = new ArrayList<String[]>();
	    
	    CSVReader csvReader = new CSVReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
	    String[] row = null;
	    int i = 0;
	    schemaRow = csvReader.readNext();
	    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	    while((row = csvReader.readNext()) != null) {  	
	    	table.add(row); 
	    	i++;
	    	if (i%10000 == 0) System.out.println(dateFormat.format(new Date())+" read " + i + " rows ...");
	    }
     
		csvReader.close();
	}
}
